package com.yvan.codeslave.batch.process;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.yvan.codeslave.batch.Consts;
import com.yvan.platform.JsonWapper;
import lombok.val;
import lombok.var;

public class ActionProcess {

    public static void process(JsonWapper jw) {

        for (val action : jw.asJsonWapperList("Actions", "Action")) {
            val type = action.asStr(Consts.ACTION_TYPE);
            var forTable = action.asStr(Consts.ACTION_FOR_TYPE);
            action.remove(Consts.ACTION_TYPE);
            action.remove(Consts.ACTION_FOR_TYPE);

            if (Strings.isNullOrEmpty(type) || !Consts.ACTION_TYPES.contains(type)) {
                throw new RuntimeException("unknown action type:" + type);
            }

            if (Strings.isNullOrEmpty(forTable)) {
                //默认第一个表格
                forTable = "Table";
            }

            //找到 action.column 中的所有列，与 table.columns 合并
            if (action.contains("Column")) {
                int sp = 1;
                final Iterable<JsonWapper> wappers = action.isArray("Column") ?
                        action.asJsonWapperList("Column") :
                        Lists.newArrayList(new JsonWapper(action.asMap("Column")));

                for (val c : wappers) {
                    if (c == null) {
                        //这是一个空位符
                        action.set(Consts.ACTION_COLUMNS, Consts.ACTION_SP + sp++, "-");
                    } else {
                        val javaName = c.asStr(Consts.COLUMN_JAVA_NAME);
                        JsonWapper jwNewColumn = new JsonWapper();
                        jwNewColumn.merge(jw.asMap(forTable, Consts.TABLE_COLUMNS, javaName));
                        jwNewColumn.merge(c.getInnerMap());
                        action.set(Consts.ACTION_COLUMNS, javaName, jwNewColumn);
                    }
                }
                action.remove("Column");
            }

            jw.set(forTable, Consts.TABLE_ACTION, type, action);
        }
        jw.remove("Actions");
    }

}
